package com.atguigu.ucenter.controller;


import com.atguigu.commonutils.R;
import com.atguigu.jwtUtils.JwtUtils;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.atguigu.ucenter.entity.Member;
import com.atguigu.ucenter.entity.vo.RegisterVo;
import com.atguigu.ucenter.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author yky
 * @since 2020-07-13
 */
@RestController
@RequestMapping("/ucenter/member")
@CrossOrigin
public class MemberController {

    @Autowired
    private MemberService memberService;

    //登录
    @PostMapping("login")
    public R login(@RequestBody Member member){
        //判断登录是否成功，使用jwt把信息封装为字符串
        if(member == null){
            return R.error().message("登录信息为空");
        }
        String token = memberService.login(member);
        return R.ok().data("token",token);
    }

    //注册
    @PostMapping("register")
    public R register(@RequestBody RegisterVo registerVo){

        memberService.register(registerVo);

        return R.ok();
    }

    //token获取用户信息
    @GetMapping("getMemberInfo")
    public  R getMemberInfo(HttpServletRequest request){
        if(!JwtUtils.checkToken(request)){
            throw new GuliException(20001,"登录已过期，请重新登录");
        }
        //从jwt中获取用户id
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        //根据id在数据库中查询
        Member member = memberService.getById(memberId);
        member.setPassword("");
        return R.ok().data("member",member);
    }

    //获取每天注册人数
    @GetMapping("getNumByDay/{day}")
    public R getNumByDay(@PathVariable("day") String day){

        Integer num = memberService.getNumByDay(day);

        return R.ok().data("num",num);
    }
}

